package com.example.mydy;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mydy.adapter.UserRewardPrivilegeAdapter;
import com.example.mydy.model.UserRewardPrivilege;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TaskRewardManagementActivity extends AppCompatActivity {

    private static final String TAG = "TaskRewardManagement";
    
    // UI组件
    private Switch taskRewardSwitch;
    private EditText taskRewardAmount;
    private EditText taskLevel1Percentage;
    private EditText taskLevel2Percentage;
    private EditText taskLevel3Percentage;
    
    private Switch inviteRewardSwitch;
    private EditText inviteRewardAmount;
    private EditText inviteLevel1Percentage;
    private EditText inviteLevel2Percentage;
    private EditText inviteLevel3Percentage;
    
    private RecyclerView recyclerViewPrivileges;
    private FloatingActionButton fabAddPrivilege;
    private Button saveSettingsButton;
    
    // 数据
    private List<UserRewardPrivilege> userRewardPrivileges = new ArrayList<>();
    private UserRewardPrivilegeAdapter privilegeAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_reward_management);
        
        // 初始化视图
        initViews();
        
        // 加载数据
        loadData();
        
        // 设置监听器
        setupListeners();
    }
    
    private void initViews() {
        // 任务奖励设置
        taskRewardSwitch = findViewById(R.id.taskRewardSwitch);
        taskRewardAmount = findViewById(R.id.taskRewardAmount);
        taskLevel1Percentage = findViewById(R.id.taskLevel1Percentage);
        taskLevel2Percentage = findViewById(R.id.taskLevel2Percentage);
        taskLevel3Percentage = findViewById(R.id.taskLevel3Percentage);
        
        // 邀请奖励设置
        inviteRewardSwitch = findViewById(R.id.inviteRewardSwitch);
        inviteRewardAmount = findViewById(R.id.inviteRewardAmount);
        inviteLevel1Percentage = findViewById(R.id.inviteLevel1Percentage);
        inviteLevel2Percentage = findViewById(R.id.inviteLevel2Percentage);
        inviteLevel3Percentage = findViewById(R.id.inviteLevel3Percentage);
        
        // 用户特权列表
        recyclerViewPrivileges = findViewById(R.id.recyclerViewPrivileges);
        recyclerViewPrivileges.setLayoutManager(new LinearLayoutManager(this));
        
        // 悬浮按钮
        fabAddPrivilege = findViewById(R.id.fabAddPrivilege);
        
        // 保存按钮
        saveSettingsButton = findViewById(R.id.saveSettingsButton);
    }
    
    private void loadData() {
        // 获取当前任务奖励设置
        double taskReward = MockDataManager.getTaskReward();
        taskRewardAmount.setText(String.valueOf(taskReward));
        
        // 获取当前分成比例设置
        double level1Ratio = MockDataManager.getDefaultLevel1Ratio();
        double level2Ratio = MockDataManager.getDefaultLevel2Ratio();
        double level3Ratio = MockDataManager.getDefaultLevel3Ratio();
        
        taskLevel1Percentage.setText(String.valueOf(level1Ratio));
        taskLevel2Percentage.setText(String.valueOf(level2Ratio));
        taskLevel3Percentage.setText(String.valueOf(level3Ratio));
        
        // 加载用户特权列表
        userRewardPrivileges.clear();
        userRewardPrivileges.addAll(MockDataManager.getUserRewardPrivileges());
        
        // 初始化适配器
        privilegeAdapter = new UserRewardPrivilegeAdapter(this, userRewardPrivileges);
        recyclerViewPrivileges.setAdapter(privilegeAdapter);
        
        // 设置邀请奖励开关和金额
        // 这里使用默认值，实际项目中应该从数据库或API获取
    }
    
    private void setupListeners() {
        saveSettingsButton.setOnClickListener(v -> saveSettings());
        
        fabAddPrivilege.setOnClickListener(v -> showAddPrivilegeDialog());
    }
    
    private void saveSettings() {
        try {
            // 保存任务奖励设置
            double taskReward = Double.parseDouble(taskRewardAmount.getText().toString());
            MockDataManager.setTaskReward(taskReward);
            
            // 保存任务分成比例
            double level1 = Double.parseDouble(taskLevel1Percentage.getText().toString());
            double level2 = Double.parseDouble(taskLevel2Percentage.getText().toString());
            double level3 = Double.parseDouble(taskLevel3Percentage.getText().toString());
            
            MockDataManager.setDefaultLevel1Ratio(level1);
            MockDataManager.setDefaultLevel2Ratio(level2);
            MockDataManager.setDefaultLevel3Ratio(level3);
            
            // 保存邀请奖励设置
            double inviteReward = Double.parseDouble(inviteRewardAmount.getText().toString());
            
            // 这里可以添加保存邀请奖励设置的代码
            // MockDataManager.setInviteReward(inviteReward);
            
            Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "奖励设置已更新：任务奖励=" + taskReward + 
                  ", 一级分成=" + level1 + "%, 二级分成=" + level2 + "%, 三级分成=" + level3 + "%");
            
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "保存设置失败：" + e.getMessage());
        }
    }
    
    private void showAddPrivilegeDialog() {
        // 显示添加用户特权对话框
        AddPrivilegeDialog dialog = new AddPrivilegeDialog();
        dialog.show(getSupportFragmentManager(), "add_privilege");
        
        // 设置回调，当用户添加特权后刷新列表
        dialog.setOnPrivilegeAddedListener(privilege -> {
            // 添加特权
            boolean success = MockDataManager.addUserRewardPrivilege(privilege);
            if (success) {
                // 刷新列表
                loadData();
                Toast.makeText(TaskRewardManagementActivity.this, "特权已添加", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TaskRewardManagementActivity.this, "添加特权失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    // 内部类：添加特权对话框
    public static class AddPrivilegeDialog extends androidx.fragment.app.DialogFragment {
        
        private EditText etUsername;
        private EditText etLevel1;
        private EditText etLevel2;
        private EditText etLevel3;
        private EditText etInviteReward;
        private EditText etRemark;
        
        private OnPrivilegeAddedListener listener;
        
        @Override
        public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
            androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(getActivity());
            
            // 加载对话框布局
            View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_add_privilege, null);
            
            // 初始化视图
            etUsername = view.findViewById(R.id.et_username);
            etLevel1 = view.findViewById(R.id.et_level1);
            etLevel2 = view.findViewById(R.id.et_level2);
            etLevel3 = view.findViewById(R.id.et_level3);
            etInviteReward = view.findViewById(R.id.et_invite_reward);
            etRemark = view.findViewById(R.id.et_remark);
            
            builder.setView(view)
                   .setTitle("添加用户特权")
                   .setPositiveButton("添加", (dialog, id) -> {
                       // 校验输入
                       if (validateInput()) {
                           // 创建特权对象
                           UserRewardPrivilege privilege = createPrivilege();
                           // 回调监听器
                           if (listener != null) {
                               listener.onPrivilegeAdded(privilege);
                           }
                       } else {
                           Toast.makeText(getActivity(), "请填写所有必填项", Toast.LENGTH_SHORT).show();
                       }
                   })
                   .setNegativeButton("取消", (dialog, id) -> dialog.dismiss());
            
            return builder.create();
        }
        
        private boolean validateInput() {
            return etUsername.getText().toString().trim().length() > 0 &&
                   etLevel1.getText().toString().trim().length() > 0 &&
                   etLevel2.getText().toString().trim().length() > 0 &&
                   etLevel3.getText().toString().trim().length() > 0 &&
                   etInviteReward.getText().toString().trim().length() > 0;
        }
        
        private UserRewardPrivilege createPrivilege() {
            String username = etUsername.getText().toString().trim();
            double level1 = Double.parseDouble(etLevel1.getText().toString().trim());
            double level2 = Double.parseDouble(etLevel2.getText().toString().trim());
            double level3 = Double.parseDouble(etLevel3.getText().toString().trim());
            double inviteReward = Double.parseDouble(etInviteReward.getText().toString().trim());
            String remark = etRemark.getText().toString().trim();
            
            return new UserRewardPrivilege(
                0, // ID 将由 MockDataManager 设置
                username,
                level1,
                level2,
                level3,
                inviteReward,
                new Date(), // 开始日期：当前日期
                null, // 结束日期：永久
                remark.isEmpty() ? "特权用户" : remark
            );
        }
        
        public void setOnPrivilegeAddedListener(OnPrivilegeAddedListener listener) {
            this.listener = listener;
        }
        
        public interface OnPrivilegeAddedListener {
            void onPrivilegeAdded(UserRewardPrivilege privilege);
        }
    }
} 